package com.system.permissiondemo.aspect;

import com.system.permissiondemo.entity.RequestLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;

/**
* @Description:    日志切面操作
* @Author:         Joe
* @CreateDate:     2020/3/18 13:11
*/
@Aspect
@Component
public class LogAspect {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    RequestLog requestLog = null;

    /**
     * 定义一个切面(第1*:所有请求；第2*:com.basic.hellorabbit.controller下所有类；第3*:所有方法；..任何参数)
     */
    @Pointcut("execution(* com.system.permissiondemo.controller.*.*(..))")
    public void logs(){
    }

    /**
     * 切面之前
     * @param joinPoint
     */
    @Before("logs()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        ArrayList<Object> objects = new ArrayList<>();
        for (int i = 0; i < args.length; i++) {
            objects.add(args[i]);
        }
        requestLog = new RequestLog(url,ip,classMethod,objects,new Date());
        //logger.info("request:{}",requestLog);
    }

    /**
     * 请求之后
     */
    @After("logs()")
    public void doAfter(){
    }

    /**
     * 方法执行完返回结果
     * @param result
     */
    @AfterReturning(returning = "result",pointcut = "logs()")
    public void doAfterReturn(Object result){
        logger.info("return:"+result);
        requestLog.setResult(result);
        /*此处可加入写入数据库操作*/
        //System.out.println(requestLog);
    }
}
